package com.yunfeisoft.interceptor;

import com.yunfeisoft.common.session.SessionModel;
import com.yunfeisoft.common.session.UserSession;
import com.yunfeisoft.common.utils.AjaxUtils;
import com.yunfeisoft.common.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录验证拦截器
 * Created by Jackie Liu on 2017/7/10.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserSession userSession;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        SessionModel sessionModel = userSession.getSessionModel();
        if (sessionModel != null) {
            request.setAttribute(Constants.SESSION_MODEL, sessionModel);
            userSession.resetSessionTime();
            return true;
        }

        String uri = request.getRequestURI().replaceFirst(request.getContextPath(), "");
        if (uri.startsWith("/view/business/mobile")) {
            response.sendRedirect(request.getContextPath() + "/mobile_login");
            return false;
        }
        if (uri.startsWith("/view")) {
            response.sendRedirect(request.getContextPath() + "/time-out");
        } else {
            AjaxUtils.ajaxJsonErrorMessage("会话失效，请重新登录");
        }
        return false;
    }
}
